package sample.plugin.language.lua.decision;

import com.rapid.api.lang.engine.highlight.decision.DecisionResult;
import com.rapid.api.lang.engine.highlight.token.TokenModel;

import io.github.rosemoe.sora.widget.schemes.EditorColorScheme;
import sample.plugin.language.base.AbstractDecision;
import sample.plugin.language.lua.LuaState;
import sample.plugin.language.lua.LuaToken;

public class LuaIdentifierDecision extends AbstractDecision<LuaState> {
    @Override
    public Iterable<DecisionResult> decide(TokenModel model, LuaState state) {
        if (model.token == LuaToken.ID) {
            TokenModel next = getNextNonEmptyToken(model);
            if (next != null) {
                if (next.token == LuaToken.LPAREN) {
                    return singleColor(EditorColorScheme.FUNCTION);
                } else if (next.token == LuaToken.DOT || next.token == LuaToken.COLON) {
                    return singleColor(EditorColorScheme.CLASS);
                } else if (next.token == LuaToken.STRING || next.token == LuaToken.ID || next.token == LuaToken.NUMBER) {
                    return singleColor(EditorColorScheme.FUNCTION);
                } else if (next.token == LuaToken.ASSIGN) {
                    return singleColor(EditorColorScheme.FIELD);
                }
            }
            TokenModel prev = getPrevNonEmptyToken(model);
            if (prev != null) {
                if (prev.token == LuaToken.DOT) {
                    return singleColor(EditorColorScheme.FIELD);
                }
            }
        }
        return refuse();
    }

    public TokenModel getNextNonEmptyToken(TokenModel model) {
        model = model.next;
        while (model != null) {
            if (model.token != LuaToken.WHITE_SPACE) {
                return model;
            }
            model = model.next;
        }
        return null;
    }

    public TokenModel getPrevNonEmptyToken(TokenModel model) {
        model = model.prev;
        while (model != null) {
            if (model.token != LuaToken.WHITE_SPACE) {
                return model;
            }
            model = model.prev;
        }
        return null;
    }
}
